/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.netbrain.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import mx.netbrain.bean.InstallBean;
import mx.netbrain.dao.PropertiesRepositoriesDao;
import mx.netbrain.dao.TreeDao;
import mx.netbrain.dao.impl.PropertiesRepositoriesDaoImpl;
import mx.netbrain.dao.impl.TreeDaoImpl;
import mx.netbrain.model.PropertiesRepositories;
import mx.netbrain.model.PropertiesRepositoriesValue;
import mx.netbrain.model.PropertiesRepositoriesValueId;
import mx.netbrain.model.Repositories;
import mx.netbrain.model.Status;
import mx.netbrain.model.Tree;
import mx.netbrain.model.User;

import org.primefaces.model.UploadedFile;

/**
 * 
 * @author Julian
 */
public class FileUploadUtil implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7661612312679509686L;

	private static char sep = File.separatorChar;

	private static BufferedReader reader;

	private static String[] props;

	@SuppressWarnings("unused")
	public static void uploadValidate(UploadedFile file, Tree treeLoad,
			User user, Long profile) {
		String extValidate;
		Tree treeNew = new Tree();
		Status status = new Status();
		Repositories repositories = new Repositories();
		String nombre = file.getFileName();
		String delimit = "[.]";
		String[] tokens = nombre.split(delimit);
		TreeDao treeDao = new TreeDaoImpl();
		if (file != null) {
			String ext = file.getFileName();
			if (ext != null) {
				extValidate = ext.substring(ext.indexOf(".") + 1);
			} else {
				extValidate = null;
			}
			try {
				transferFile(file.getFileName(), file.getInputstream(), file,
						treeLoad.getRoute());
			} catch (IOException e) {
				FacesContext context = FacesContext.getCurrentInstance();
				context.addMessage(null, new FacesMessage("Wrong",
						"Error al cargar archivo."));
			}
			status.setId(1);
			if (tokens.length > 0) {
				treeNew.setName(tokens[0]);
				treeNew.setExtension(tokens[1]);
			} else {
				treeNew.setName(tokens[0]);
			}
			treeNew.setRoot(treeLoad.getId());
			treeNew.setRoute(treeLoad.getRoute());
			treeNew.setSize(file.getSize() + "");
			treeNew.setType("Documento");
			treeNew.setRegister(new Date());
			treeNew.setUser(user);
			treeNew.setRepositories(treeLoad.getRepositories());
			treeNew.setMime(file.getContentType());
			treeDao.save(treeNew);
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null,
					new FacesMessage("Succefull", file.getFileName()
							+ " se cargo correctamente!"));
		} else {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					"Error", "Seleccione un archivo.");
			FacesContext.getCurrentInstance().addMessage(null, message);
		}
	}

	public static void uploadFileTmp(UploadedFile file, Tree[] selectedTrees) {
		if (file != null) {
			for (int i = 0; i < selectedTrees.length; i++) {
				if (selectedTrees[i].getType().equals("Documento")) {
					findFileProperties(file, selectedTrees[i].getId());
				}
			}
		}
	}

	public static void findFileProperties(UploadedFile file, Long id) {
		Tree tree = new Tree();
		List<PropertiesRepositories> listProperties = new ArrayList<PropertiesRepositories>();
		TreeDao treeDao = new TreeDaoImpl();
		tree = treeDao.findById(id);
		PropertiesRepositoriesDao propertiesRepositoriesDao = new PropertiesRepositoriesDaoImpl();
		listProperties = propertiesRepositoriesDao.listForRepositories(tree
				.getRepositories());
		props = new String[listProperties.size()];
		if (file != null) {
			String line = "";
			InstallBean installBean = new InstallBean();
			String TMP_PATH = installBean.getEstructure();
			try {
				transferFile(file.getFileName(), file.getInputstream(), file,
						TMP_PATH + "tmp" + sep);
				reader = new BufferedReader(new FileReader(TMP_PATH + "tmp"
						+ sep + file.getFileName()));
				while ((line = reader.readLine()) != null) {
					StringTokenizer delimitador = new StringTokenizer(line, "|");
					Long idFile = Long
							.parseLong(delimitador.nextToken().trim());
					if (id.equals(idFile)) {
						for (int i = 0; i < props.length; i++) {
							PropertiesRepositoriesDao propertiesDao = new PropertiesRepositoriesDaoImpl();
							PropertiesRepositoriesValue propertiesValue = new PropertiesRepositoriesValue();
							PropertiesRepositoriesValueId propertiesValueId = new PropertiesRepositoriesValueId();
							propertiesValueId.setProperties(listProperties.get(
									i).getId());
							propertiesValueId.setRepository(tree
									.getRepositories().getId());
							propertiesValueId.setTree(tree.getId());
							propertiesValue.setId(propertiesValueId);
							propertiesValue.setValue(delimitador.nextToken()
									.trim());
							propertiesDao.saveValue(propertiesValue);
						}
						break;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void transferFile(String fileName, InputStream in,
			UploadedFile file, String destination) {
		try {
			OutputStream out = new FileOutputStream(new File(destination
					+ fileName));
			int reader = 0;
			byte[] bytes = new byte[(int) file.getSize()];
			while ((reader = in.read(bytes)) != -1) {
				out.write(bytes, 0, reader);
			}
			in.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	public static void editFile(Tree treeEdit) {
		Tree tree = new Tree();
		TreeDao treeDao = new TreeDaoImpl();
		tree = treeDao.findById(treeEdit.getId());
		File antiguo = new File(tree.getRoute() + tree.getName() + "."
				+ tree.getExtension());
		File nuevo = new File(treeEdit.getRoute() + treeEdit.getName() + "."
				+ tree.getExtension());
		treeDao.update(treeEdit);
		antiguo.renameTo(nuevo);
	}
}
